
import ru.hh.team02.chat.database.DatabaseServiceInterface;
import ru.hh.team02.chat.messaging.MessageDbEntry;
import ru.hh.team02.chat.utils.HashMapWithLock;

import java.util.ArrayList;
import java.util.List;


public class SuperScalableNoSqlDbWithSharding implements DatabaseServiceInterface {
    HashMapWithLock<String, String> passwordByUser = new HashMapWithLock<String, String>();
    HashMapWithLock<Integer, MessageDbEntry> messageById = new HashMapWithLock<Integer, MessageDbEntry>();

    static volatile int id = 0;

    public SuperScalableNoSqlDbWithSharding() {
        passwordByUser.put("test1", "test1");
        passwordByUser.put("test2", "test2");
        passwordByUser.put("test3", "test3");
    }

    public boolean clientExists(String name) {
           return passwordByUser.containsKey(name);
    }


    @Override
    public String getPasswordByClientName(String name) {
        assert(clientExists(name));
        return passwordByUser.get(name);
    }

    @Override
    public String getRoomNameByClientName(String name) {
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public int putNewPersonalMessageIntoDatabase(String message, String recepientName) {
        synchronized (this) {
            System.out.println(message + " in the database");

            messageById.put(id, new MessageDbEntry(id, recepientName, message, false));
            return id++;
        }
    }

    @Override
    public boolean markPersonalMessageAsDelivered(int id) {
        synchronized (this) {
            if (!messageById.containsKey(id)) {
                return false;
            }

            MessageDbEntry entry =  messageById.get(id);
            entry.Status = true;
            System.out.println(entry.Message + " marked");
            return true;
        }
    }

    @Override
    public List<MessageDbEntry> getAllUndeliveredMessagesToTheClient(String clientName) {
        synchronized (this) {
            List<MessageDbEntry> result = new ArrayList<MessageDbEntry>();
            for (int key : messageById.keySet()) {
                MessageDbEntry entry = messageById.get(key);
                if (entry.Recepient.equals(clientName) && entry.Status == false) {
                    result.add(entry);
                }
            }
            return result;
        }
    }

    @Override
    public MessageDbEntry getMessagesById(int id) {
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public String[] getAllRooms() {
        return new String[0];  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void changeRoom(String clientName, String room) {
        //To change body of implemented methods use File | Settings | File Templates.
    }
}
